import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
// create an axios instance
const service = axios.create({
  baseURL:'http://47.113.113.50:129/', // api 的 base_url
  timeout: 50000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    // if (store.getters.token) {
      // laravel令牌验证headers
      config.headers['Authorization'] = 'Bearer ' + window.sessionStorage.getItem('token');
      config.headers['Accept'] = 'application/json'
   
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(res => {
   // Loading.service().close();
   console.log(res.status)

   if (res.status !== 200) {
     Message({
       message: res.data.errmsg || 'Error',
       type: 'error',
       duration: 5 * 1000
     })
    if (res.data.errno === 501) {
        router.push('/login')
        return;
    } else if (res.data.errno === 403) {
        return Message.error('权限不足,请联系管理员!');
    }
    return Promise.reject(new Error(res.data.errmsg || 'Error'))
} else {
    return res;
}
    
}, err => {
   // Loading.service().close();

    Message({
        message: err.response.data.errmsg,
        type: 'error',
        duration: 5 * 1000
    })
    return Promise.reject(err)
})

export default service
